package com.lpwa.framework.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.ByteOrder;

/**
 * @author June
 * @description
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyInitializer extends ChannelInitializer {

    @Autowired
    public MyByteEncoder myByteEncoder;

    @Override
    protected void initChannel(Channel channel) throws Exception {
        //创建一个通道初始化对象(匿名对象)
        //给pipeline 设置处理器
        //可以使用一个集合管理 SocketChannel,再推送消息时,可以将业务加入到各个channel对应的NIOEventLoop的taskQueue
        // 或者 scheduleTaskQueue
        log.info("客户socketchannel hashcode=" + channel.hashCode());
        //入站解码
        //channel.pipeline().addLast(new MyByteToLongDecoder2());

        //出站编码"decoder",
//        channel.pipeline().addLast(new MyByteEncoder());
//        channel.pipeline().addFirst(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN,Integer.MAX_VALUE,1,2,3,0,true));
//        channel.pipeline().addLast(new NettyServerHandler());
        channel.pipeline().addLast(new MyByteEncoder());
        ByteBuf delimiter = Unpooled.copiedBuffer("$EOF".getBytes());
        channel.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,delimiter));
        channel.pipeline().addLast(new NettyServerHandler());
    }
}